package com.zzyl.nursing.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.nursing.service.WechatService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
@Service
public class WechatServiceImpl implements WechatService {
    @Value("${wechat.appId}")
    private String appid;
    @Value("${wechat.appSecret}")
    private String appSecret;
    private static final String OPENID_URL="https://api.weixin.qq.com/sns/jscode2session";
    private static final String ACCESSTOKEN_URL="https://api.weixin.qq.com/cgi-bin/token";
    private static final String PHONENUM_URL="https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=";

    private HashMap<String,Object> getCommonMap(){
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appid);
        paramMap.put("secret", appSecret);
        return paramMap;

    }

    @Override
    public String getOpenId(String code) {
        HashMap<String, Object> commonMap = this.getCommonMap();
        commonMap.put("js_code",code);
        commonMap.put("grant_type","authorization_code");
        String s = HttpUtil.get(OPENID_URL, commonMap);

        JSONObject entries = JSONUtil.parseObj(s);
        String o = entries.getStr("openid");
        if (StrUtil.isNotBlank(o)) {
            return o;
        }else {
            throw new BaseException("获取openid失败");
        }
    }
    private String getAccessToken(){
        HashMap<String, Object> commonMap = this.getCommonMap();
        commonMap.put("grant_type","client_credential");
        String s = HttpUtil.get(ACCESSTOKEN_URL, commonMap);
        JSONObject entries = JSONUtil.parseObj(s);
        String o = entries.getStr("access_token");
        if (StrUtil.isNotBlank(o)){
            return o;
        }else {
            throw new BaseException("获取token失败");
        }
    }

    @Override
    public String getPhoneNum(String code) {
        HashMap<String, Object> map = new HashMap<>();
        map.put("code",code);
        String post = HttpUtil.post(PHONENUM_URL + this.getAccessToken(), JSONUtil.toJsonStr(map));

        if (StrUtil.isNotBlank(post)){
            JSONObject entries = JSONUtil.parseObj(post);
            String o = entries.getStr("phone_info");
            String o1 = JSONUtil.parseObj(o).getStr("phoneNumber");
            return o1;
        }else {
            throw new BaseException("获取手机号失败");
        }


    }
}
